#include "ScriptDelegateImplement.h"

#include "Reflection/FunctionList.h"

#include "Reflection/Function.h"


CAny SScriptDelegateBase::ScriptInvoke(const TVector<CAny> &InArguments)
{
    
    CAny Result;

    for(int32_t i=0;i<Bindings.Num();i++)
    {
        auto& Binding=Bindings[i];
               
        if(!Binding.IsValid())
        {
            Bindings.Remove(Binding);
            i--;
            continue;
        }
    }

    SDecoratedType ReturnType=FunctionType->GetReturnType();
    if(ReturnType.BasicType==WH::TReflectionType<void>::FindOrCreateType())
    {
        for(auto& Binding:Bindings)
        {
            Binding.Function->Invoke(InArguments);
        }
    }
    else
    {
        for(auto& Binding:Bindings)
        {
            CAny Temp=Binding.Function->Invoke(InArguments);
            if(Temp.GetType())
            {
                Result=Temp;
            }
        }

        if(Result.GetType()==nullptr)
        {
            SDecoratedType ReturnType=FunctionType->GetReturnType();
            Result=CAny(ReturnType.BasicType,ReturnType.BasicType->CreateInstance());
        }
    }
    
    return Result;
}
